<template>
  <div class="store-manage-container">
    <div class="header">
      
      <el-button type="primary" @click="handleAddStore">新增门店</el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="storeList"
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="门店ID" width="80" />
      <el-table-column prop="name" label="门店名称" />
      <el-table-column prop="manager" label="负责人" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="latitude" label="纬度" width="100" />
      <el-table-column prop="longitude" label="经度" width="100" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" link @click="handleEditStore(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDeleteStore(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑门店对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="storeForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="门店名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="formData.manager" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { StoreInfo } from '@/api/types/store'
import { getStoreList, addStore, updateStore, deleteStore } from '@/api/store'

// 数据和状态
const loading = ref<boolean>(false)
const storeList = ref<StoreInfo[]>([])
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref<string>('')
const formData = ref({
  id: 0,
  name: '',
  manager: '',
  address: '',
  latitude: 0,
  longitude: 0
})
const rules = ref({
  name: [{ required: true, message: '门店名称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '地址不能为空', trigger: 'blur' }]
})

// 定义 storeForm 并将其初始化为 null
const storeForm = ref(null)

// 获取门店列表
const fetchStoreList = async () => {
  loading.value = true
  try {
    const response = await getStoreList()
    if (response.code === '200') {
      storeList.value = response.result
    } else {
      ElMessage.error(response.msg || '获取门店列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败，请稍后重试')
  }
  loading.value = false
}

// 新增门店
const handleAddStore = () => {
  dialogTitle.value = '新增门店'
  formData.value = {
    id: 0,
    name: '',
    manager: '',
    address: '',
    latitude: 0,
    longitude: 0
  }
  dialogVisible.value = true
}

// 编辑门店
const handleEditStore = (row: StoreInfo) => {
  dialogTitle.value = '编辑门店'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  storeForm.value?.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (formData.value.id === 0) {
          // 新增
          const addParams = {
            name: formData.value.name,
            manager: formData.value.manager,
            address: formData.value.address
          }
          response = await addStore(addParams)
        } else {
          // 修改
          const updateParams = {
            id: formData.value.id,
            name: formData.value.name,
            manager: formData.value.manager,
            address: formData.value.address
          }
          response = await updateStore(updateParams)
        }
        
        if (response.code === '200') {
          ElMessage.success(response.msg || (formData.value.id === 0 ? '新增成功' : '修改成功'))
          dialogVisible.value = false
          await fetchStoreList()
        } else {
          ElMessage.error(response.msg || (formData.value.id === 0 ? '新增失败' : '修改失败'))
        }
      } catch (error) {
        ElMessage.error('请求失败，请稍后重试')
      }
    }
  })
}

// 删除门店
const handleDeleteStore = (id: number) => {
  ElMessageBox.confirm('确定要删除该门店吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteStore({ id })
      if (response.code === '200') {
        ElMessage.success(response.msg || '删除成功')
        await fetchStoreList()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('请求失败，请稍后重试')
    }
  }).catch(() => {})
}

// 生命周期钩子
onMounted(() => {
  fetchStoreList()
})
</script>

<style lang="scss" scoped>
.store-manage-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>

<style lang="scss" scoped>
.store-manage-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>